##!/usr/bin/env python
# coding=utf-8
#--------------------------------------------------------------------------
# 文件名:       wpSend.py 
# 说明：        目的、作用说明
#
# 版本：        0.03
# 作者：        xiao
#
# 创建时间：    2011-04-01 
# 许可证：      Apache License V2.0
#--------------------------------------------------------------------------

import os
import sqlite3DB
import random
import ConfigParser
import WpXMLRPC
import time
import XiaoTool as xt

class wpSend:

	def __init__(self, site="slimming-products-introduced.com"):
		self.path = "/root/tohealth"
		self.blog_url = site
		self.time1 = time.time()
		self.main()

	## 加载配置
	#
	def main(self):
		config = ConfigParser.ConfigParser()
		config.readfp(open("%s/wp_config.ini" % self.path))

		self.blog_type = config.get("blog", "blog_type")
		self.blog_user_pass = config.get("blog", "blog_user_pass")
		html_tmp = config.get("blog", "html_tmp")
		self.blog_key=config.get("blog", "blog_key")

		self.blog_post_num = config.get("send", "blog_post_num")
		self.time_if = config.get("send", "time_if")
		self.one_time = config.get("send", "one_time")
		self.two_time = config.get("send", "two_time")
		self.three_time = config.get("send", "three_time")
		self.fove_time = config.get("send", "fove_time")
		self.point_num = config.get("send", "point_num")
		self.strat = config.get("send", "strat")

		self.dbname = config.get("init", "dbname")

		if not os.path.isfile(html_tmp):
			html_tmp = "send.html"
		tmpFile = open("%s/%s" % (self.path, html_tmp))
		self.tmpStr = tmpFile.read()
		tmpFile.close()

		if not os.path.isfile("%s/%s" % (self.path, self.dbname)):
			xt.setTimeLog("数据库文件不存在！")
			exit()

		xt.setTimeLog("请稍等，%s 日志发送中！" % self.blog_url)
		num = self.send_post()
		xt.setTimeLog("%s 日志发送 %s 篇完毕！TIME：%s" % (self.blog_url, num, time.time()-self.time1))
	#------------------------------------------ End def main()


	## 提交日志的主方法
	#
	def send_post(self):
		f = open("%s/%s" % (self.path, self.blog_key))
		flist = [l.strip() for l in f.readlines()]
		f.close()

		fname = open("%s/%s.ini" % (self.path, self.blog_url))
		fnamelist = [l.strip() for l in fname.readlines()]
		fname.close()


		db = sqlite3DB.DbAction("%s/%s" % (self.path, self.dbname))
		db.dbLoad()

		proSqlQuery = db.query("SELECT id, name, price, features, description, asin FROM `product`;")
		proDict = dict([(str(id),[name, price, features, description, asin]) for id, name, price, features, description, asin in proSqlQuery])

		sendSqlQuery = db.query("SELECT id, sendid FROM `send` WHERE flag=0 LIMIT %s, %s;" % (self.strat, self.blog_post_num))
		db.dbClose()

		ids = []
		idone = 1
		for id, sendid in sendSqlQuery:
			if os.path.isfile("stop"):
				xt.setTimeLog("User ation stop!")
				exit()

			sendids = sendid.split(",")
			random.shuffle(sendids)

			# 组装 blog 内容
			title = ""
			description = ""
			asinStr = "http://www.amazon.com/gp/product/{asin}/ref=as_li_qf_sp_asin_tl?ie=UTF8&tag=tohealth-20&linkCode=as2&camp=217153&creative=399349&creativeASIN={asin}"
			desTop = ""
			mt_keywords = []
			blogNums = ["%s" % i for i in range(1, 6)]
			for proId in sendids:
				proName = proDict[proId][0]

				proNameSp = proName.split()
				lenNameNum = len(proNameSp) - 2
				if lenNameNum <= 0:
					continue

				ramNum = random.randint(-lenNameNum, lenNameNum)
				if ramNum == 0:
					ramNum = -2

				if title == "":
					title = " ".join(proNameSp[ramNum:])
				else:
					title += ", %s" % " ".join(proNameSp[ramNum:])

				# 处理 asin
				desTop += "<a href='%s' target='_blank' rel='nofollow'>%s</a><br />" % (asinStr.replace("{asin}", str(proDict[proId][4])), proName)

				# 处理属性
				jsonAttr = {"price":proDict[proId][1], "features":proDict[proId][2]}
				attrsStr = "<div>%s</div><div>features: %s</div>" % (proDict[proId][1], proDict[proId][2])

				random.shuffle(blogNums)
				description += self.tmpStr.replace("{name}", proName).replace("{attrs}", attrsStr).replace("{doc}", proDict[proId][3]).replace("{url}", asinStr.replace("{asin}", str(proDict[proId][4]))).replace("{jsnum}", blogNums.pop())
				if "<!--more-->" not in description:
					description += "\n<!--more-->\n"

				mt_keywords.append(proName)

				for keyStr in random.sample(flist, 5):
					mt_keywords.append(keyStr)


			title = title.title().replace("&Apos;", "&apos;")

			wp = WpXMLRPC.WpXMLRPC("http://%s" % self.blog_url, random.sample(fnamelist, 1)[0], self.blog_user_pass, self.blog_type)

			try:
				des_on = desTop + description
				wp.newPost({"title":title, "description":des_on, "mt_keywords":mt_keywords})
			except:
				continue
			ids.append(str(id))
			if len(ids)%int(self.point_num) == 0:
				break

		db.dbLoad()
		db.save("UPDATE `send` SET flag=1 WHERE id in (%s);" % ",".join(ids))
		sendSqlQuery = db.query("SELECT id, sendid FROM `send` WHERE flag=0")
		db.dbClose()

		return len(ids)
	#------------------------------------------ End def send_post()

if __name__ == "__main__":
	time.sleep(random.randint(0, 1000))
	wpSend()

	if random.randint(0, 1) == 1:
		time.sleep(random.randint(0, 1000))
		wpSend()
